1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { return reBuild(pre, in, 0, pre.length-1, 0, in.length-1); }
public TreeNode reBuild(int[] pre, int[] in, int preStart, int preEnd, int inStart, int inEnd) { if (preStart >= preEnd) { if (preStart == preEnd) { return new TreeNode(pre[preStart]); } return null; } int inRoot = find(inStart, inEnd, pre[preStart], in); int lengthOfLeft = inRoot - inStart; TreeNode root = new TreeNode(pre[preStart]); root.left = reBuild(pre, in, preStart+1, preStart+lengthOfLeft, inRoot-lengthOfLeft, inRoot-1); root.right = reBuild(pre, in, preStart+lengthOfLeft+1, preEnd, inRoot+1, inEnd); return root; } public int find(int start, int end, int val, int[] in) { for (int i = start; i <= end; i++) { if (val == in[i]) { return i; } } return -1; } }
|